﻿
using System.Data;
using MySqlConnector;

namespace From._1124;

public partial class BookMain : Form
{
    public BookMain()
    {
        InitializeComponent();
    }

    private void BookMain_Load(object sender, EventArgs e)
    {
        //初始化操作
        //查询所有图书
        GetAllBooks();
        



        //查询所有图书分类
        GetAllCategories();
    }

    private void GetAllCategories()
    {
        using var connection =
            new MySqlConnection(
                "server=localhost;port=3306;database=book;user=root;password=123456;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
        connection.Open();
        string sql = "SELECT * FROM book_info";
        //创建适配器对象
        MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection);
        //创建数据集
        DataSet dataSet = new DataSet();
        //填充数据
        adapter.Fill(dataSet, "book_category");
        //绑定数据
        DataTable? dataTable = dataSet.Tables["book_category"];
        //插入全部行
        DataRow row = dataTable.Rows[0];
        row[0] = "全部";
        dataTable.Rows.InsertAt(row, 0);
        //绑定数据
        this.comboBox1.DataSource = dataTable;
        this.comboBox1.DisplayMember=dataTable.Columns[0].ColumnName;

    }

    private void GetAllBooks()
    {
        using var connection = new MySqlConnection("server=localhost;port=3306;database=book;user=root;password=123456;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
        connection.Open();
        string sql = "SELECT * FROM books_info";
        //创建适配器对象
        MySqlDataAdapter adapter=new MySqlDataAdapter(sql ,connection);
        //创建数据集
        DataSet dataSet = new DataSet();
        //填充数据
        adapter.Fill(dataSet, "books_info");
        //绑定数据
        this.dataGridView1.DataSource = dataSet.Tables["books_info"];
    }

    private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
    {
       DialogResult result= MessageBox.Show("确定要删除此条数据吗?",caption:"警告"，MessageBoxButtons.OKCancel);
       if (result == DialogResult.OK)
       {
           int bookId = (int)this.dataGridView1.SelectedRows[0].Cells[0].Value;
           using var connection = new MySqlConnection("server=localhost;port=3306;database=book;user=root;password=123456;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
           connection.Open();
           string sql="delect from books_info where book_id=@bookId";
           //创建command 对象
           using var command=new MySqlCommand(sql,connection);
           command.Parameters.AddWithValue("@bookId",bookId);
           //执行删除方法
           int count = command.ExecuteNonQuery();
           if (count > 0)
           {
               MessageBox.Show("删除成功");
               GetAllBooks();
           }
           else
           {
               MessageBox.Show("删除失败");
           }
       }
    }
}